package handler

import (
	"chirp-read/cache"
	"chirp-read/models"
	"chirp-read/pkg"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"strconv"
	"time"
)

func UsersLogin(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	redis_key := "users_login_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount == 3 {
		c.JSON(200, gin.H{
			"code": "500",
			"msg":  "密码错误三次,禁止登录",
		})
		return
	}
	var users models.User
	err := models.DB.Where("username = ?", username).Find(&users).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询用户失败",
		})
		return
	}
	if users.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if users.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误三次,封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": users,
	})
}
func UsersRoleAdd(c *gin.Context) {
	uid, _ := strconv.Atoi(c.Query("uid"))
	rid, _ := strconv.Atoi(c.Query("rid"))
	data := models.UserRole{
		Model: gorm.Model{},
		Uid:   uid,
		Rid:   rid,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func RoleNodeAdd(c *gin.Context) {
	rid, _ := strconv.Atoi(c.Query("rid"))
	nid, _ := strconv.Atoi(c.Query("nid"))
	data := models.RoleNode{
		Rid: rid,
		Nid: nid,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func UserRoleList(c *gin.Context) {
	/*SELECT
	*
		FROM
	roles
	LEFT JOIN user_roles ON user_roles.rid = roles.id
	WHERE
	user_roles.uid = 1*/
	uid := c.Query("uid")
	var userRole models.UserRole
	models.DB.Table("roles").
		Joins("left join user_roles on user_roles.rid=roles.id").
		Where("user_roles.uid = ?", uid).Find(&userRole)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "OK",
		"data": userRole,
	})
}
func RoleNodeList(c *gin.Context) {
	/*SELECT
	*
		FROM
	nodes
	LEFT JOIN role_nodes ON role_nodes.nid = nodes.id
	WHERE
	role_nodes.rid = 1*/
	rid := c.Query("rid")
	var roleNode models.RoleNode
	models.DB.Table("nodes").
		Joins("left join role_nodes on role_nodes.nid=nodes.id").
		Where("role_nodes.rid = ?", rid).Find(&roleNode)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": roleNode,
	})
}
func UsersList(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var users []models.User
	redis_key := "users_list_page_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Find(&users)
		jsonData, _ := json.Marshal(cacheData)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &users)
	}
	var total int64
	models.DB.Model(&models.User{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  users,
		"total": total,
	})
	return
}
func UsersDetail(c *gin.Context) {
	id := c.Query("Id")
	var users models.User
	redis_key := "users_detail_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("id = ?", id).Find(&users)
		jsonData, _ := json.Marshal(cacheData)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &users)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": users,
	})
	return
}
